package org.choviwu.top.qg.util;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.choviwu.top.qg.constant.SmallConstant;
import org.choviwu.top.qg.constant.WxcpConstant;

import java.text.MessageFormat;
import java.util.Map;

/***
 *
 **/
public class WxcpUtils {

    private static final String accessToken = " https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
    private static final String userList = " https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={0}&department_id={1}&fetch_child={2}";


    private static final String sendMsg = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";



    public static String getAccessToken(WxcpConstant wxcpConstant){
        HttpResponse httpResponse = HttpUtil.createGet(MessageFormat.format(accessToken, SmallConstant.appId, wxcpConstant.getSecret()))
                .execute();
        return JsonUtils.toObj(httpResponse.body(), Map.class)
                .get("access_token").toString();
    }

    public static JSONArray getUserList(){
        HttpResponse httpResponse = HttpUtil.createGet(MessageFormat.format(userList, getAccessToken(WxcpConstant.record),1,1))
                .execute();
        Map map = JsonUtils.toObj(httpResponse.body(), Map.class);
       return new JSONArray(map.get("userlist"));
    }



    public static void sendMsg(String toUser,String title,String content,String id){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser",toUser);
        jsonObject.put("msgtype","textcard");
        jsonObject.put("agentid",WxcpConstant.daily.getAgentId());
        JSONObject text = new JSONObject();
        text.put("title",title);
        text.put("description",content);
        text.put("url","https://choviwu.top/archives/"+id);
        jsonObject.put("textcard",text);
        HttpResponse httpResponse = HttpUtil.createPost(MessageFormat.format(sendMsg, getAccessToken(WxcpConstant.daily)))
                .body(jsonObject.toString())
                .execute();
        Map map = JsonUtils.toObj(httpResponse.body(), Map.class);
        System.out.println(map);
    }


}
